﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace AzureDiagMon.Common.Helpers
{
    [Serializable]
    public sealed class CacheFile<T>
    {
        public T[] Items { get; set; }

        private string fileName;
        public string FileName
        {
            get { return fileName; }
        }

        private static readonly string cachePath = Path.Combine(PathHelper.AppDataFolder, "Cache", typeof(T).Name);

        private CacheFile() { }

        public CacheFile(IEnumerable<T> items)
        {
            Items = items.ToArray();

            if (!Directory.Exists(cachePath))
                Directory.CreateDirectory(cachePath);

            fileName = Path.Combine(cachePath, String.Concat(Guid.NewGuid().ToString(), ".xml"));
            var serializer = new XmlSerializer(GetType());
            using (var fileSteam = new FileStream(FileName, FileMode.CreateNew))
            {
                serializer.Serialize(fileSteam, this);
            }
        }

        public static CacheFile<T> Load(string fileName)
        {
            var serializer = new XmlSerializer(typeof(CacheFile<T>));
            using (var fileSteam = new FileStream(fileName, FileMode.Open))
            {
                var result = serializer.Deserialize(fileSteam) as CacheFile<T>;
                if (result != null)
                {
                    result.fileName = fileName;
                }
                return result;
            }
        }

        public static IEnumerable<CacheFile<T>> GetCacheFiles()
        {
            return Directory.GetFiles(cachePath).Select(Load);
        }

        public void Delete()
        {
            File.Delete(fileName);
        }
    }
}
